/* BEGIN JS DOCUMENT READY RENDERING */
$("#menu").click(function(){
	$("#menu").toggleClass("active");
	toggleMenu();
});

/* when the window is being resized it needs to ensure 
	that contentbody and both sidebar are shown when 
	in max size mode. Also the userbox needs to be aligned
	in the center, if visible */
$(window).resize(function() {
	if(window.innerWidth>=930){
		$(".contentbody").show();
		$(".sidebar").show();		
	}else{
		toggleMenu();
	}
});

/* attach to search field */
$("#headersearchtext").keyup(function(event){
	if ( event.which == 13 ) {
		location.href = "/s/"+escape(event.target.value)
				+"?ga_search_keyword="+escape(event.target.value);
  	}
});

/* attach to login buttons */
$(".loginbutton").click(function(event){
	// parse the provider name out of the button
	var providerName = event.target.id;
	providerName = providerName.substring(0,providerName.indexOf("_"));

	// notify analytics about the login attempt
	authtrack('LoginAttempt',providerName);

	// send the user to the OAuth URL
	location.href="/auth/"+providerName;
});

/* attach to logout buttons */
$(".logoutbutton").click(function(){
	// notify analytics about the logout attempt
	// and use the default ga variable 
	authtrack('LogoutAttempt',ga_auth_provider);

	// redirect user to logout url
	location.href="/logout";
});

function toggleMenu(){
	/* show sidebar when menu active, otherwise don't */
	if($("#menu").hasClass("active")){
		$(".contentbody").hide();
		$(".sidebar").show();
	}else{
		$(".contentbody").show();
		$(".sidebar").hide();
	}
}

/* attach comment text functions */
if($("#newcommenttext").length>0){
	/* vertically resizes the comment text area when typing */
	$("#newcommenttext").keyup(function(e) {
	    while($(this).outerHeight() < this.scrollHeight 
	    	+ parseFloat($(this).css("borderTopWidth")) 
	    	+ parseFloat($(this).css("borderBottomWidth"))) {
	        $(this).height($(this).height()+1);
	    };
	});

	var commentDefaulText = "";
	$(document).ready(function(){
		commentDefaulText = $("#newcommenttext").val();
	});

	$("#newcommenttext").focus(function(){
		if($("#newcommenttext").val()==commentDefaulText){
			$("#newcommenttext").val("");
		}
	});

	$("#newcommenttext").focusout(function(){
		if($("#newcommenttext").val()==""){
			$("#newcommenttext").val(commentDefaulText);
		}
	});

	/* submit comment form when button is clicked */
	$("#submitcommentbutton").click(function(){
		$("#submitcommentform").submit();
	});

	/* attach function to delete link */
	if($(".deletecommentlink").length>0){
		$(".deletecommentlink").click(function(){
			var commentId = $(this).attr("id").substring(18);
			$("#commententrydelete_"+commentId).hide();
			$("#commententryconfirmdelete_"+commentId).show();
		});

		$(".deletecommentconfirmlink").click(function(){
			var deleteCommentId = $(this).attr("id").substring(25);
			$("#deleteComment").val(deleteCommentId);
			$("#deleteCommentForm").submit();
		});
	}
}

/* validates an email address*/
function isValidEmailAddress(emailAddress){
	var result = false;
	var email_regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,10})+$/;

	if(email_regex.test(emailAddress)){
  		result = true;
  	}

	return result;
}

/* validates a phone number */
function isValidPhoneNumber(phoneNumber){
	var result = false;
	var phone_regex = /^\+([0-9]{5,20})$/;

	if(phone_regex.test(phoneNumber)){
		result = true;
	}

	return result;
}

/* this function checks the operating system 
	through the user agent and determines whether 
	the system is WhatsApp compatible or not. 

	Current supported systems: 
	Android, iOS, BB, WinPhone

	Older Nokia systems such as the S60 series
	are not supported here as I do not know whether
	they can handle the link or not.
	*/
function isWhatsAppCompatible(){
	var result = false;

	var compatibleAgentList = ["android","ipad","iphone",
		"blackberry","playbook","windows phone"];

	for(var a=0;a<compatibleAgentList.length;a++){
		if(navigator.userAgent.toLowerCase().indexOf
					(compatibleAgentList[a])>0){
			result = true;
		}
	}

	return result;
}

/* check if there is a whatsapp button and the 
	system is whatsapp compatible. If that's the 
	case then show the whatsapp button */
if($("#whatsappbuttoncontainer").length>0
	&&isWhatsAppCompatible()==true){
	// enable the whatsapp button
	$("#whatsappbuttoncontainer").show();
}

/* attach email subscription to button */
$("#sidebarboxemailbutton").click(function(){
	if(isValidEmailAddress($("#sidebarboxemailfield").val())){
  		$("#sidebaremailsubscribeform").submit();
  	}
});

/* attach notification bar close button */
if($("#notificationbarclosebutton").length>0){
	$("#notificationbarclosebutton").click(function(){
		$("#notificationbar").slideUp(500);
	});
}

/* attach contact form function */
if($("#contactform").length>0){
	var defaultContactMessage = $("#contactmessage").val();
	$("#contactmessage").focus(function(){
		if($("#contactmessage").val()==defaultContactMessage){
			$("#contactmessage").val("");
		}
	});

	$("#contactmessage").focusout(function(){
		if($("#contactmessage").val().length==0){
			$("#contactmessage").val(defaultContactMessage);
		}
	});


	$("#contactsendbutton").click(function(){
		// ensure all fields are filled properly:
		// email, name and message is mandatory, phone is optional
		if($("#contactname").val().length>0
			&&isValidEmailAddress($("#contactemail").val())==true
			&&(isValidPhoneNumber($("#contactphone").val())==true
				||$("#contactphone").val().length==0)
			&&$("#contactmessage").val().length>0
			&&$("#contactmessage")!=defaultContactMessage){
			// all fields are filled as required
			// now submit the contact form
			$("#contactform").submit();
		}else{
			// fields are not sufficiently completed
			if($("#contactname").val().length==0){
				$("#contactname").addClass("contactformfielderror");
			}

			// display the field in red when the email address is wrong
			if(isValidEmailAddress($("#contactemail").val())==false){
				$("#contactemail").addClass("contactformfielderror");
			}

			// display error when the phone is not empty and invalid
			if(isValidPhoneNumber($("#contactphone").val())==false
				&&$("#contactphone").val().length>0){
				$("#contactphone").addClass("contactformfielderror");
			}

			// ensure the message is not empty
			if($("#contactmessage").val().length==0
				||$("#contactmessage").val()==defaultContactMessage){
				$("#contactmessage").addClass("contactformfielderror");
			}
		}
	});
}

/* attach newsletter functions */
if($("#newslettersignupbutton").length>0){
	// replace 00 with + in the country code
	$("#newsletterphonenumber").keyup(function(){
		if($("#newsletterphonenumber").val().length>4
			&&$("#newsletterphonenumber").val().substring(0,2)=="00"){
			$("#newsletterphonenumber").val("+"+$("#newsletterphonenumber").val().substring(2));
		}
	});

	$("#newslettersignupbutton").click(function(){
		if(isValidEmailAddress($("#newsletteremailaddress").val())==true
			&&($("#newsletterphonenumber").val()==""
				||isValidPhoneNumber($("#newsletterphonenumber").val())==true)){
			// all data valid, post the form
			$("#newslettersignupform").submit();
		}else{
			// mark email field red when its data is invalid
			if(!isValidEmailAddress($("#newsletteremailaddress").val())){
				$("#newsletteremailaddress").addClass("newslettersignupfielderror");
			}

			// mark phone field red when data provided is invalid
			if($("#newsletterphonenumber").val()!=""
				&&isValidPhoneNumber($("#newsletterphonenumber").val())==false){
				$("#newsletterphonenumber").addClass("newslettersignupfielderror");
			}
		}
	});

	$("#newsletterunsubscribelink").click(function(){
		if(!isValidEmailAddress($("#newsletteremailaddress").val())){
			$("#newsletteremailaddress").addClass("newslettersignupfielderror");
		}else{
			$("#unsubscribe_email").val($("#newsletteremailaddress").val());
			$("#newsletterunsubscribeform").submit();
		}	
	});
}